<?php
/**
 * CmsController
 *
 * PHP Version 5.4
 *
 * @author liuxuTJ <liuxuphp@icesmart.cn>
 */
namespace Admin\Controller;
use Admin\Service\BaseService;
use Admin\Service\PermissionService;
use Admin\Service\UserService;
use Model\NewsModel;
use Think\Controller;

/**
 * Class CmsController
 */
class CmsController extends BaseController {

    public function __construct()
    {
        parent::__construct();
        $userService = new UserService();
        $userInfo = $userService->validateLogin();   //验证是否登录

        $permissionService = new PermissionService();
        $permission = $permissionService->validate($userInfo['userId'], [
            'editNews' => '/' . CONTROLLER_NAME . '/editNews',
        ]);
        $menu = $permissionService->menu($userInfo['userId']);
        $this->assign('permission', $permission);

        $this->assign('menu', $menu);
        $this->assign('userInfo', $userInfo);
    }

    public function index()
    {
        $newsModel = new NewsModel();
        $page             = $this->page($newsModel, null);
        $show             = $page->show();
        $list  = $newsModel->limit($page->firstRow . ',' . $page->listRows)->select();

        $this->assign('list', $list);
        $this->assign("page", $show);
        $this->display();
    }

    public function editNews(){
        $id = I("get.id");
        if(empty($id)){
            $this->error("非法参数","/Admin");
        }
        $newsModel =new NewsModel();
        $data = $newsModel->find($id);
        $this->assign("data",$data);
        $this->display();
    }

    public function modifyNews(){

        $data = [
            'title'       => I("post.title"),
            'description' => I("post.description"),
            'content'     =>I("post.content")
        ];

        $image = $_FILES['image'];
        $id   = intval(I("post.id"));
        if (empty($data['title'])) {
            $this->error("标题不可为空");
        }
        if(!empty($image['name'])){
            $baseService = new BaseService();
            $image = $baseService->upload($image);
            $data['image'] = $image;
        }

        $newsModel = new NewsModel();
        $news      = $newsModel->update($data, $id);
        if ($news) {
            $this->success("修改成功");
        } else {
            $this->error("修改失败");
        }

    }
}